package com.weilele.mvvm.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext


/**
 * 描述：mvvm--基类ViewModel
 * 尽可能以函数为主，处理UI的逻辑操作
 */
abstract class MvvmViewModel : ViewModel() {

    /**
     * 存储Model
     */
    val modelList = mutableListOf<MvvmModel>()

    /**
     * 创建Model
     */
    inline fun <reified T : MvvmModel> getModel(): T {
        for (mvvmModel in modelList) {
            if (mvvmModel is T) {
                return mvvmModel
            }
        }
        val instance = T::class.java.newInstance()
        modelList.add(instance)
        return instance
    }

    /**
     * 创建Model
     */
    fun createModel(cls: Class<*>): Any {
        for (mvvmModel in modelList) {
            if (mvvmModel.javaClass.simpleName == cls.simpleName) {
                return mvvmModel
            }
        }
        val instance = cls.newInstance()
        modelList.add(instance as MvvmModel)
        return instance
    }

    /**
     * 做一写清理操作
     */
    override fun onCleared() {
        modelList.forEach {
            it.onCleared()
        }
        modelList.clear()
        super.onCleared()
    }

    /**
     * 利用viewModelScope（作用域）启动一个协程
     *  viewModelScope 默认运行再 代码块运行在主线程
     */
    fun launchWithScope(
            context: CoroutineContext = EmptyCoroutineContext,
            start: CoroutineStart = CoroutineStart.DEFAULT,
            block: suspend CoroutineScope.() -> Unit
    ): Job {
        return viewModelScope.launch(context, start, block)
    }

    /**
     * 利用viewModelScope（作用域）启动一个协程
     *  CoroutineStart.DEFAULT 代码块运行在主线程
     */
    fun <T> asyncWithScope(
            context: CoroutineContext = EmptyCoroutineContext,
            start: CoroutineStart = CoroutineStart.DEFAULT,
            block: suspend CoroutineScope.() -> T
    ): Deferred<T> {
        return viewModelScope.async(context, start, block)
    }
}